#include "Acceptor.h"
#include "TcpConnection.h"
#include "EventLoop.h"
#include <iostream>
#include <unistd.h>

using std::cout;
using std::endl;

//1、连接建立做的事件
void onNewConnection(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has connected!" << endl;
}

//2、消息到达做的事件
void onMessage(const TcpConnectionPtr &con)
{
    string msg = con->receive();//接收客户端的数据
    cout << ">>recv msg from client " << msg << endl;

    //接收到客户端的msg之后，是可以进行业务逻辑的处理
    /* msg += "wangdao"; */

    //数据发回给客户端
    con->send(msg);
}

//3、连接断开做的事件
void onClose(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has closed!" << endl;
}

void test()
{
    Acceptor acceptor("127.0.0.1", 8888);
    acceptor.ready();//此时处于监听状态

    EventLoop loop(acceptor);
    loop.setNewConnectionCallback(std::move(onNewConnection));
    loop.setMessageCallback(std::move(onMessage));
    loop.setCloseCallback(std::move(onClose));
    loop.loop();
}

int main(int argc, char **argv)
{
    test();
    return 0;
}

